import { setQuery } from '../setQuery';
import safeStringify from "../safeStringify";
import urlEncode from "../urlEncode";

export const getRequestConfig = ({
    url,
    method = 'get',
    postType = 'url',
    data = {},//url中的params
    body = {},
    headers = {},
    withCredentials = true
} = {}) => {
    const _method = method.toUpperCase();
    const config = {
        body,
        method: _method,
        headers: {
            ...headers
        }
    };

    let _url;
    if (_method === 'GET') {
        _url = setQuery(url, {
            ...data,
            ...body
        });
        delete config.body;
    } else {
        _url = setQuery(url, data);
    }
    config.url = _url;

    if (_method === 'POST') {
        setPostData(config, postType);
    }

    config.mode = 'cors';
    if (withCredentials) {
        config.credentials = 'include';
    }
    return config;
};

const setPostData = (config, postType) => {
    const _headers = config.headers;
    if (postType === 'json') {
        _headers['Content-Type'] = 'application/json';
        config.body = safeStringify(config.body);
    } else if (postType === 'url') {
        _headers['Content-Type'] = 'application/x-www-form-urlencoded';
        config.body = urlEncode(config.body);
    }
};
export default getRequestConfig;